package com.zhanghe.wzq.handler.request;

import com.zhanghe.wzq.Table;
import com.zhanghe.wzq.User;
import com.zhanghe.wzq.command.request.StartGameRequest;
import com.zhanghe.wzq.command.response.StartGameResponse;
import com.zhanghe.wzq.data.Attributes;
import com.zhanghe.wzq.data.TableManager;
import com.zhanghe.wzq.data.UserChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * StartGameRequestHandler
 *
 * @author Clevo
 * @date 2018/12/30
 */
public class StartGameRequestHandler extends SimpleChannelInboundHandler<StartGameRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, StartGameRequest startGameRequest) throws Exception {
        User current = channelHandlerContext.channel().attr(Attributes.USER).get();
        if(current!=null){
            Table table = TableManager.INSTANCE.getUserTable(current.getId());
            TableManager.StartGameVO startGameVO = TableManager.INSTANCE.startGame(table.getId());
            if(startGameVO.isSuccess()){
                StartGameResponse startGameResponse = new StartGameResponse();
                startGameResponse.setSuccess(true);
                startGameResponse.setColor(table.getGame().getUserColor(current.getId()));
                channelHandlerContext.channel().writeAndFlush(startGameResponse);

                String anotherUserId = table.getGame().getAnotherUser(current.getId());
                Channel anotherChannel = UserChannelManager.getInstance().getUserChannel(anotherUserId);
                StartGameResponse anotherStartGameResponse = new StartGameResponse();
                anotherStartGameResponse.setSuccess(true);
                anotherStartGameResponse.setColor(table.getGame().getUserColor(anotherUserId));
                anotherChannel.writeAndFlush(anotherStartGameResponse);
            }else{
                StartGameResponse startGameResponse = new StartGameResponse();
                startGameResponse.setSuccess(false);
                channelHandlerContext.channel().writeAndFlush(startGameResponse);
            }
        }
    }
}
